package com.googlecode.i78ba.util;

import java.io.File;
import java.io.FileInputStream;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.xml.transform.stream.StreamSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.stereotype.Component;

import com.googlecode.i78ba.util.configbean.PlatformConfig;

@Component
public class PlatformConfigListener implements ServletContextListener,InitializingBean {

	private static Logger log = LoggerFactory
			.getLogger(PlatformConfigListener.class);

	private static String webRoot;

	public static String getWebRoot() {
		return webRoot;
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {

	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		webRoot = servletContextEvent.getServletContext().getRealPath("/");
		log.debug("init webRoot -> " + webRoot);
	}

	@Autowired
	private Marshaller marshaller;
	@Autowired
    private Unmarshaller unmarshaller;
	
	private static PlatformConfig platformConfig;

	public static PlatformConfig getPlatformConfig() {
		return platformConfig;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		File serverMod = new File(getClass().getResource("/platform-config.xml").getFile());
		platformConfig = (PlatformConfig)unmarshaller.unmarshal(new StreamSource(new FileInputStream(serverMod)));
		log.debug("init platformConfig");
		for(String name:platformConfig.getMods().keySet()){
			log.debug("init mod -> " + name + " - " + platformConfig.getMods().get(name).getPath());
		}
	}
}
